"use client"

import type React from "react"

import { useState, useRef } from "react"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader } from "@/components/ui/card"
import { toast } from "@/components/ui/use-toast"
import Sidebar from "@/components/sidebar"
import { verifySignature } from "@/lib/api"

interface VerificationResult {
  threshold: number
  distance: number
  match: boolean
}

export default function VerificationPage() {
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [previewUrl, setPreviewUrl] = useState<string | null>(null)
  const [verifying, setVerifying] = useState(false)
  const [result, setResult] = useState<VerificationResult | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    setSelectedFile(file)

    // Create preview URL
    const reader = new FileReader()
    reader.onload = () => {
      setPreviewUrl(reader.result as string)
    }
    reader.readAsDataURL(file)

    // Reset result when new file is selected
    setResult(null)
  }

  const handleVerify = async () => {
    if (!selectedFile) {
      toast({
        title: "请选择文件",
        description: "请先上传需要验证的签名图片",
        variant: "destructive",
      })
      return
    }

    setVerifying(true)
    try {
      const result = await verifySignature(selectedFile)
      setResult(result)
    } catch (error) {
      console.error("Verification failed:", error)
      toast({
        title: "验证失败",
        description: "签名验证过程中发生错误，请稍后再试",
        variant: "destructive",
      })
    } finally {
      setVerifying(false)
    }
  }

  const handleSelectAnotherFile = () => {
    setSelectedFile(null)
    setPreviewUrl(null)
    setResult(null)

    if (fileInputRef.current) {
      fileInputRef.current.value = ""
    }
  }

  return (
    <div className="flex h-screen bg-gray-100">
      <Sidebar />

      <main className="flex-1 p-8 overflow-y-auto">
        <h2 className="text-3xl font-bold mb-6">手写签名认证</h2>

        {/* 上传待认证签名 */}
        <div className="mb-6">
          <h3 className="text-2xl font-semibold mb-4">上传待认证签名</h3>

          <div className="p-4 border-2 border-gray-300 rounded-lg">
            <Card className="overflow-hidden">
              <CardHeader className="p-4 border-b border-gray-200">
                <h4 className="text-lg font-semibold">待认证签名</h4>
              </CardHeader>

              <CardContent className="p-4 flex flex-col items-center">
                {previewUrl ? (
                  <div className="relative w-40 h-40">
                    <Image
                      src={previewUrl || "/placeholder.svg"}
                      alt="待认证签名"
                      fill
                      className="object-contain rounded-lg"
                    />
                  </div>
                ) : (
                  <div className="w-40 h-40 border-2 border-dashed border-gray-300 rounded-lg flex items-center justify-center mb-4">
                    <p className="text-gray-500 text-center px-4">请上传待认证的签名图片</p>
                  </div>
                )}

                <div className="mt-4 flex space-x-2">
                  {!previewUrl ? (
                    <>
                      <input
                        ref={fileInputRef}
                        type="file"
                        id="signatureToVerify"
                        accept="image/*"
                        onChange={handleFileChange}
                        className="hidden"
                      />
                      <Button onClick={() => fileInputRef.current?.click()} variant="outline">
                        选择图片
                      </Button>
                    </>
                  ) : (
                    <>
                      <Button onClick={handleSelectAnotherFile} variant="outline">
                        选择其他图片
                      </Button>
                      <Button onClick={handleVerify} disabled={verifying}>
                        {verifying ? "认证中..." : "认证签名"}
                      </Button>
                    </>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        {/* 认证结果 */}
        {result && (
          <div className="mt-8">
            <Card className={`p-6 border-2 border-dashed ${result.match ? "border-green-500" : "border-red-500"}`}>
              <h3 className="text-2xl font-semibold mb-4">认证结果</h3>
              <p>
                <strong>签名阈值：</strong> {result.threshold.toFixed(6)}
              </p>
              <p>
                <strong>与数据库中最接近签名的距离：</strong>
                <span className={result.match ? "text-green-500" : "text-red-500"}> {result.distance.toFixed(6)}</span>
              </p>
              <p className={`mt-4 ${result.match ? "text-green-500" : "text-red-500"}`}>
                <strong>认证结果：</strong>{" "}
                {result.match ? "签名与该用户已上传的签名匹配，认证通过" : "签名与该用户已上传的签名不匹配，认证失败"}
              </p>
            </Card>
          </div>
        )}
      </main>
    </div>
  )
}
